import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/prescription.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../router/router.dart';

/// @Author lixiaobin
/// @Date 2024/2/20
/// @Description 开单记录
class PrescriptionRecordPage extends StatefulWidget {
  const PrescriptionRecordPage({super.key});

  @override
  State<PrescriptionRecordPage> createState() => _PrescriptionRecordPageState();
}

class _PrescriptionRecordPageState extends State<PrescriptionRecordPage>
    with SingleTickerProviderStateMixin {
  final _textController = TextEditingController();
  late TabController _tabController;
  final _tabArr = ['全部', '已支付', '未支付'];
  final _prescriptionList = <Prescription>[];
  var _isPrint = 0;
  var _pageNo = 1;
  final _pageSize = 20;
  final _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    _pageNo = 1;
    _getPrescriptionList();
  }

  void _onLoading() async {
    _pageNo++;
    _getPrescriptionList();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabArr.length, vsync: this);
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
            color: ColorRes.colorf9f9fa,
            child: Column(
              children: [
                _buildSearchView(),
                _buildTaberView(),
                _buildListView()
              ],
            )));
  }

  /// 搜索
  Widget _buildSearchView() {
    return Container(
        color: ColorRes.white,
        child: Container(
          height: 40.w,
          padding: EdgeInsets.only(left: 8.w, right: 8.w),
          margin:
              EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w, bottom: 8.w),
          decoration: BoxDecoration(
              color: ColorRes.colorf5f5f5,
              borderRadius: BorderRadius.circular(6.w)),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ImageLoader.loadAsset('icon_search.png', 18.w),
              SizedBox(width: 8.w),
              Expanded(
                  child: TextField(
                      controller: _textController,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (str) => _onRefresh(),
                      onChanged: (str) => _onRefresh(),
                      style: TextStyle(
                          color: ColorRes.color333333, fontSize: 14.sp),
                      decoration: const InputDecoration(
                          hintText: '请输入患者姓名',
                          hintStyle: TextStyle(color: ColorRes.colorc3c3c3),
                          border: InputBorder.none)))
            ],
          ),
        ));
  }

  /// tab view
  Widget _buildTaberView() {
    return Container(
        color: ColorRes.white,
        child: TabBar(
          controller: _tabController,
          onTap: (int index) {
            _isPrint = index;
            _onRefresh();
          },
          indicatorColor: ColorRes.colorMain,
          labelColor: ColorRes.colorMain,
          unselectedLabelColor: ColorRes.color333333,
          indicatorSize: TabBarIndicatorSize.label,
          tabs: _tabArr.map((e) => Tab(text: e)).toList(),
        ));
  }

  Widget _buildListView() {
    return Expanded(child: _buildSmartRefresher());
  }

  /// 刷新组件
  Widget _buildSmartRefresher() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _prescriptionList.isEmpty
            ? CommWidget.buildEmptyView(tipStr: '您还没有开单记录哦！')
            : ListView.builder(
                shrinkWrap: true,
                itemBuilder: (c, i) => _buildItem(c, i),
                itemCount: _prescriptionList.length,
              ));
  }

  /// 列表item
  Widget _buildItem(BuildContext c, int i) {
    var prescription = _prescriptionList[i];
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          context.push(
              '${PageUrl.prescriptionPreView}?prescriptionNo=${prescription.prescriptionNo}');
        },
        child: Container(
            margin: EdgeInsets.only(top: 10.w, left: 16.w, right: 16.w),
            decoration: BoxDecoration(
                color: ColorRes.white,
                borderRadius: BorderRadius.circular(6.w)),
            child: Column(
              children: [
                SizedBox(height: 19.w),
                Row(
                  children: [
                    SizedBox(width: 16.w),
                    Text(
                      '就诊人：${prescription.patientName ?? ''}',
                      style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 17.sp,
                          fontWeight: FontWeight.bold),
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 4.w, right: 4.w),
                      margin: EdgeInsets.only(left: 5.w),
                      decoration: BoxDecoration(
                          color: ColorRes.colore6e6ff,
                          borderRadius: BorderRadius.circular(4.w)),
                      child: Text(
                        '门',
                        style: TextStyle(
                            color: ColorRes.colorMain, fontSize: 13.sp),
                      ),
                    ),
                    Visibility(
                        visible: prescription.type == '9',
                        child: Container(
                          padding: EdgeInsets.only(left: 4.w, right: 4.w),
                          margin: EdgeInsets.only(left: 5.w),
                          decoration: BoxDecoration(
                              color: ColorRes.colorfeeed0,
                              borderRadius: BorderRadius.circular(4.w)),
                          child: Text(
                            '配方颗粒',
                            style: TextStyle(
                                color: ColorRes.colorfca912, fontSize: 13.sp),
                          ),
                        ))
                  ],
                ),
                SizedBox(height: 11.w),
                CommWidget.buildLine(
                  margin: EdgeInsets.only(left: 16.w, right: 16.w),
                ),
                SizedBox(height: 11.w),
                Row(
                  children: [
                    SizedBox(width: 16.w),
                    Expanded(
                        child: Text(
                      '开单时间：${prescription.createTime?.substring(0, 10)}',
                      style: TextStyle(
                          color: ColorRes.color9A9A9A, fontSize: 13.sp),
                    )),
                    Expanded(
                        child: Text(
                      prescription.isPrint == '1' ? '已支付' : '未支付',
                      textAlign: TextAlign.end,
                      style: TextStyle(
                          color: prescription.isPrint == '1'
                              ? ColorRes.colorc1c1c1
                              : ColorRes.colorec6755,
                          fontSize: 14.sp),
                    )),
                    SizedBox(width: 16.w),
                  ],
                ),
                SizedBox(height: 11.w),
              ],
            )));
  }

  /// 获取开单列表
  _getPrescriptionList() async {
    var user = App.instance.userInfo;
    var patientName = _textController.text.trim().toString();
    var body = {
      'doctorId': user?.id ?? '',
      'pageIndex': _pageNo,
      'pageSize': _pageSize,
    };
    if (_isPrint != 0) body['isPrint'] = _isPrint == 1 ? '1' : '0';
    if (patientName != '') body['patientName'] = patientName;
    var response = await HttpClient.postJson(
        HttpRequest(Api.findPrescriptionListNew, body: body));
    var serviceResult = ServiceResult<List<Prescription>>.list(response,
        (map) => (map ?? []).map((e) => Prescription.fromJson(e)).toList());

    if (serviceResult.success) {
      var list = serviceResult.responseBody;
      if (_pageNo == 1) {
        _prescriptionList.clear();
      }
      _prescriptionList.addAll(list ?? []);
    }

    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
    setState(() {});
  }
}
